package com.shaun.tea.config;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


public class OperatePicUtils {

    private static String path = "D:/img";

    public static List<String> uploadPics(List<MultipartFile> files) throws Exception {
        List<String> fileNames = new ArrayList<>();
        for (MultipartFile file : files) {
            fileNames.add(uploadPic(file));
        }
        return fileNames;
    }

    public static String uploadPic(MultipartFile file) throws Exception {
        //获取文件名称
        String beforeFileName = file.getOriginalFilename();
        //获取文件名后缀
        String afterFileName;
        String suffix = beforeFileName.substring(file.getOriginalFilename().lastIndexOf("."));
        suffix = suffix.toLowerCase();
        if (suffix.equals(".jpg") || suffix.equals(".jpeg") || suffix.equals(".png")/* || suffix.equals(".gif")*/) {
            afterFileName = UUID.randomUUID().toString() + suffix;
            File targetFile = new File(path, afterFileName);
            if (!targetFile.getParentFile().exists()) {    //注意，判断父级路径是否存在
                targetFile.getParentFile().mkdirs();
            }
            long size = 0;
            //保存
            try {
                file.transferTo(targetFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            throw new Exception("格式有误，请上传.jpg、.png、.jpeg格式的文件");
        }
        return afterFileName;
    }

    public static void deletePic(String fileName) {
        File file = new File(path + "\\" + fileName);
        file.delete();
    }

}
